package com.along.study.Config;

import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import io.netty.util.internal.StringUtil;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ProxyConstant {

    public static final String REMOTE_CLIENT = "remote-client";
    public static final String HANDLER_ONE = "preHandler";
    public static final String HANDLER_TOW = "afterHandler";

    /** 绑定channel_id */
    public static final AttributeKey<String> VID = AttributeKey.newInstance("vid");

    public static final AttributeKey<String> CLIENT_CODE = AttributeKey.newInstance("clientCode");


    /** 客户端id 客户端服务channel */
    public static Map<String, Channel> clientChannelMap = new ConcurrentHashMap<>();


    /** 访客，客户端服务channel */
    public static Map<String, Channel> chient_channel = new ConcurrentHashMap<>();

    /** 访客，访客服务channel */
    public static  Map<String, Channel> visitor_channel = new ConcurrentHashMap<>();


    /**
     * 清除连接
     *
     * @param vid 访客ID
     */
    public static  void clearVccVvc(String vid) {
        if (StringUtil.isNullOrEmpty(vid)) {
            return;
        }
        Channel clientChannel = chient_channel.get(vid);
        if (null != clientChannel) {
            clientChannel.attr(VID).set(null);
            chient_channel.remove(vid);
        }
        Channel visitorChannel = visitor_channel.get(vid);
        if (null != visitorChannel) {
            visitorChannel.attr(VID).set(null);
            visitor_channel.remove(vid);
        }
    }

    /**
     * 清除关闭连接
     *
     * @param vid 访客ID
     */
    public static void clearVccVvcAndClose(String vid) {
        if (StringUtil.isNullOrEmpty(vid)) {
            return;
        }
        Channel clientChannel = chient_channel.get(vid);
        if (null != clientChannel) {
            clientChannel.attr(VID).set(null);
            chient_channel.remove(vid);
            clientChannel.close();
        }
        Channel visitorChannel = visitor_channel.get(vid);
        if (null != visitorChannel) {
            visitorChannel.attr(VID).set(null);
            visitor_channel.remove(vid);
            visitorChannel.close();
        }
    }
}
